import requests
import ctypes
from PIL import Image, ImageDraw
import time
import os
import json
import hashlib
from shutil import copyfile

Image.MAX_IMAGE_PIXELS = None
root = None


def GetMD5FromLocalFile(filename):
    with open(filename, 'rb') as fp:
        data = fp.read()
    file_md5 = hashlib.md5(data)
    return file_md5.hexdigest()


def download_jpg(FengYunName, file_name):
    if FengYunName == '风云4A':
        url = 'http://img.nsmc.org.cn/CLOUDIMAGE/FY4A/MTCC/FY4A_DISK.JPG'
    else:
        url = 'http://img.nsmc.org.cn/CLOUDIMAGE/FY4B/AGRI/GCLR/FY4B_DISK_GCLR.JPG'

    response = requests.get(url)
    with open(file_name, "wb") as file:
        file.write(response.content)


# 获取屏幕分辨率
def get_screen():
    user32 = ctypes.windll.user32
    screen_width = user32.GetSystemMetrics(0)
    screen_height = user32.GetSystemMetrics(1)
    info = {
        'width': screen_width,
        'height': screen_height
    }
    return info


# 获取图像像素
def get_imginfo(file_name):
    image = Image.open(file_name)
    width, height = image.size
    return (width, height)


# 缩放图片
def suofangjpg(file_name, suofang):
    jpginfo = get_imginfo(file_name)
    screeninfo = get_screen()
    ratio = min(screeninfo['width'] / jpginfo[0], screeninfo['height'] / jpginfo[1]) * suofang
    # ratio = min(screeninfo['width'] / jpginfo[0], screeninfo['height'] / jpginfo[1]) * 1
    new_weight = int(jpginfo[0] * ratio)
    new_height = int(jpginfo[1] * ratio)
    oldimage = Image.open(file_name)
    newimage = oldimage.resize((new_weight, new_height))
    # newimage = oldimage.resize((new_weight, new_height),box=(440,0,1760, 743))
    newimage.save(file_name)


# 黑色幕布
def mubu(screen):
    width = screen['width']
    height = screen['height']

    image = Image.new('RGB', (width, height), (0, 0, 0))
    image.save('img/background.jpg')


# 居中合成壁纸
def heceng_jpg(file_name_1, file_name_2):
    background_img = Image.open(file_name_2)
    foreground_img = Image.open(file_name_1)

    # 计算前景图像放置的位置
    x = (background_img.width - foreground_img.width) // 2
    y = (background_img.height - foreground_img.height) // 2

    # 将前景图像居中放置到背景图像上
    background_img.paste(foreground_img, (x, y))

    # 显示合成后的图像
    # background_img.show()

    # 保存合成后的图像
    background_img.save(f"img/new1.jpg")


# 绘制圆形
def crop_circle(image_path, output_path):
    # 打开图像
    image = Image.open(image_path)

    # 创建一个与图像大小相同的透明图层
    mask = Image.new('L', image.size, 0)

    # 创建一个绘图对象，并在图层上绘制圆形
    width, height = image.size
    draw = ImageDraw.Draw(mask)
    draw.ellipse((0, 0, width, height), fill=255)

    # 将图像应用到掩膜上，只保留圆形区域
    result = Image.new('RGB', image.size)
    result.paste(image, mask=mask)

    # 保存结果图像
    result.save(output_path)


# 设置壁纸
def set_wallpaper(image_path):
    # 调用 Windows API 函数来设置壁纸
    current_dir = os.getcwd() + '/img/wallpaper.bmp'
    image = Image.open(image_path)
    image.save("img/wallpaper.bmp", "BMP")
    image_dir = os.getcwd() + '/img/wallpaper.bmp'
    ctypes.windll.user32.SystemParametersInfoW(20, 0, image_dir, 3)
    # ctypes.windll.user32.SystemParametersInfoW(20, 0, r"C:\软件\风云壁纸\img\wallpaper.bmp", 3)


# 下载并设置为壁纸
def setFengYun():
    with open('img/cofig.json') as f:
        # 将文件内容解析为 JSON 数据
        data = json.load(f)
    suofangnum = float(data['suofang'])
    # shuaxing = int(data['shuaxing'])
    weixingname = data['weixing']
    MD5_1=None
    if os.path.exists('img/tmp.jpg') == True:
        MD5_1 = GetMD5FromLocalFile('img/tmp.jpg')
        # print(MD5_1)
    download_jpg(weixingname, 'img/tmp.jpg')
    MD5_2 = GetMD5FromLocalFile('img/tmp.jpg')
    # print(MD5_2)
    if MD5_1==None or MD5_2 != MD5_1:
        copyfile('img/tmp.jpg', 'img/image.jpg')
        # print('down')
        for i in range(60, 0, -1):
            if os.path.exists(f'img/new{i}.jpg') == True:
                if i < 60:
                    os.rename(f'img/new{i}.jpg', f'img/new{i+1}.jpg')
                else:
                    os.remove(f'img/new{i}.jpg')
        suofangjpg('img/image.jpg', suofangnum)
        crop_circle('img/image.jpg', 'img/image.jpg')
        mubu(get_screen())
        heceng_jpg('img/image.jpg', 'img/background.jpg')


i = 60
t = 1
if os.path.exists(f'img/new1.jpg') != True:
    setFengYun()
while True:
    with open('img/cofig.json') as f:
        data = json.load(f)
        # timenum = 2
        timenum = int(data['shuaxing']) * 60
    if t > timenum:
        setFengYun()
        t = 0
    if os.path.exists(f'img/new{i}.jpg') == True:
        set_wallpaper(f'img/new{i}.jpg')
    else:
        i -= 1
        continue
    i -= 1
    t += 1
    if i <1:
        i = 60
    # print(i,t)
    time.sleep(1)
